package com.huiminpay.transaction.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.util.StringUtil;
import com.huiminpay.transaction.api.IAppPlatformChannelService;
import com.huiminpay.transaction.entity.AppPlatformChannel;
import com.huiminpay.transaction.mapper.AppPlatformChannelMapper;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

@Service
public class IAppPlatformChannelServiceImpl implements IAppPlatformChannelService {


    @Autowired
    AppPlatformChannelMapper appPlatformChannelMapper;


    @Override
    public Integer queryAppBindPlatformChannel(String appId, String platformChannelCodes) {
        //非空校验
        if (StringUtil.isEmpty(appId)){
            throw new BusinessException(CommonErrorCode.E_200202);
        }
        if (StringUtil.isEmpty(platformChannelCodes)){
            throw new BusinessException(CommonErrorCode.E_200202);
        }
        //根据AppID和platformChannel来查询应用是否已绑定服务
        QueryWrapper<AppPlatformChannel> qw = new QueryWrapper<>();
        qw.lambda().eq(AppPlatformChannel::getAppId, appId).eq(AppPlatformChannel::getPlatformChannel, platformChannelCodes);
        Integer integer = appPlatformChannelMapper.selectCount(qw);

        return integer;
    }

    @Override
    public void insertAppPlatformChannel(String appId, String platformChannelCodes) throws BusinessException {

        //校验非空
        if (StringUtil.isEmpty(appId)){
            throw new BusinessException(CommonErrorCode.E_300003);
        }
        if (StringUtil.isEmpty(platformChannelCodes)){
            throw new BusinessException(CommonErrorCode.E_300004);
        }

        //需要验证应用是否已经绑定过该服务
        QueryWrapper<AppPlatformChannel> qw = new QueryWrapper<>();
        qw.lambda().eq(AppPlatformChannel::getAppId,appId).
                eq(AppPlatformChannel::getPlatformChannel,platformChannelCodes);
        Integer integer = appPlatformChannelMapper.selectCount(qw);
        if (integer > 0){
            throw new BusinessException(CommonErrorCode.E_300005);
        }

        //如果没有绑定过该应用的话，进行应用和平台服务的绑定
        AppPlatformChannel appPlatformChannel = new AppPlatformChannel();
        appPlatformChannel.setAppId(appId);
        appPlatformChannel.setPlatformChannel(platformChannelCodes);
        appPlatformChannelMapper.insert(appPlatformChannel);

    }


}
